/*oOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO

Authors: Nitay Megides
		 Rachel Banino

Project: Exercise 2

Description:
A general module for general functions. Used throughout the project
oOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO*/

#define _CRT_SECURE_NO_WARNINGS

#include "General.h"
#include <stdlib.h>
#include <tchar.h>
#include "TestManager.h"

BOOL VerifyMemory(void* ptr)
{
    if (ptr == NULL) 
    { 
        printf("Error: Out of memory!\n");
		return FALSE;
    }

	return TRUE;
}

BOOL VerifyFileOpen(void* ptr)
{
    if (ptr == NULL) 
    { 
        printf("Error: File could not be opened\n"); 
        return FALSE;
    }

	return TRUE;
}

void ReportThreadError()
{
	printf("Thread Error!");
}

void ReportLoadError()
{
    printf("Tests File Invalid!");
}

void ReportTestErrors()
{
    printf("Some tests had errors!");
}

EFileCompareResult CompareFiles( TCHAR* filename1, TCHAR* filename2 )
{
	FILE* file1 = NULL, *file2 = NULL;
	void* fileBuffer1 = NULL, *fileBuffer2 = NULL;
	int fileSize1 = 0, fileSize2 = 0;
	EFileCompareResult result = FILECOMPARE_ERROR;

	// First try to open the files
	file1 = _tfopen(filename1, TEXT("rb"));
	file2 = _tfopen(filename2, TEXT("rb"));

	if (!VerifyFileOpen(file1) || !VerifyFileOpen(file2))
		return FILECOMPARE_ERROR;


	// Get file sizes
	fseek(file1, 0, SEEK_END);
	fseek(file2, 0, SEEK_END);
	fileSize1 = ftell(file1);
	fileSize2 = ftell(file2);

	// Check if the sizes match
	result = FILECOMPARE_DIFFERENT;
	if (fileSize1 == fileSize2)
	{
		// Sizes match, read files
		fileBuffer1 = malloc(fileSize1);
		fileBuffer2 = malloc(fileSize2);

		result = FILECOMPARE_ERROR;
		if (VerifyMemory(fileBuffer1) && VerifyMemory(fileBuffer2))
		{
			rewind(file1);
			rewind(file2);

			if ((fread(fileBuffer1, 1, fileSize1, file1) == fileSize1) &&
				(fread(fileBuffer2, 1, fileSize2, file2) == fileSize2))
			{
				if (memcmp(fileBuffer1, fileBuffer2, fileSize1) == 0)
					result = FILECOMPARE_IDENTICAL;
                else
                    result = FILECOMPARE_DIFFERENT;
			}
		}
	}

	fclose(file1);
	fclose(file2);

	return result;
}


void ReportThreadExitCode( DWORD exitCode )
{
	switch (exitCode)
	{
	case THREAD_TEST_COMPLETED_SUCCESSFULLY:
		// Do nothing
		break;
	case THREAD_TEST_ERROR:
		printf("Test Failed on thread!!");
		break;
	case THREAD_ERROR:
		ReportThreadError();
		break;
	default:
		break; 
	}
}
